package demo1;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {
    //定义一个阻塞队列组织任务
    private  BlockingQueue<Runnable> queue=new LinkedBlockingQueue<>();
    private  Thread[] threads;

    /**
     * 提交一个任务到线程到线程池的任务队列
     * @param runnable 具体的任务
     * @throws InterruptedException
     */
    public  void submit(Runnable runnable) throws InterruptedException {
        if (runnable==null) {
            throw new IllegalArgumentException("任务不能为空");
        }
        queue.put(runnable);
    }

    //工厂模式来创建实例
    public static MyThreadPool createMyThreadPool(int initialCapacity){
        MyThreadPool myThreadPool=new MyThreadPool();
        Thread[] threads=new Thread[initialCapacity];
        for (int i = 0; i < threads.length; i++) {
            threads[i]=new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Runnable runnable=myThreadPool.queue.take();
                            runnable.run();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            },String.valueOf(i));
            threads[i].start();
        }
        return myThreadPool;
    }


}
